//
//  LKOpenShopStepThreeViewController.m
//  Mideleague_Agent
//
//  Created by Zhiwang on 2020/6/4.
//  Copyright © 2020 Zhiwang. All rights reserved.
//

#import "LKOpenShopStepThreeViewController.h"
#import "LKUFPictureRow.h"
#import "LKUFPictureRowCell.h"
#import "LKUFOpenShopHeaderRow.h"
#import "LKUFOpenShopHeaderRowCell.h"
#import "LKUFOpenShopBottomButtonRow.h"
#import "LKUFOpenShopBottomButtonRowCell.h"
#import "LKOpenShopStepFourViewController.h"
@interface LKOpenShopStepThreeViewController (){
    dispatch_group_t _group;
    dispatch_queue_t _queue;
    dispatch_semaphore_t semaphore;
}


@property(nonatomic,strong)UFFormView *formview;
@property(nonatomic,strong)NSMutableArray *dataArray;
@property(nonatomic,assign)NSInteger pictureTapSelectIndex;
@property(nonatomic,strong)UIImage *selcetedUploadImage;
@end

@implementation LKOpenShopStepThreeViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    self.navigationItem.title = @"商户开通";
    _group = dispatch_group_create();
    _queue = dispatch_queue_create("seriersQueue", DISPATCH_QUEUE_SERIAL);
      semaphore  = dispatch_semaphore_create(1);
    [self setNavgationRightBtn];
    self.dataArray = [[NSMutableArray alloc] initWithArray:@[@"ic_main_member_manage",@"ic_main_member_manage",@"ic_main_member_manage"]];
    if (self.inforModel.id_number_end_time == nil) {
        self.inforModel.id_number_end_time = @"";
    }
    if (self.inforModel.id_number_start_time == nil) {
        self.inforModel.id_number_start_time = @"";
    }
    [self createFormView];
    // Do any additional setup after loading the view.
}
-(void)setNavgationRightBtn{
    WS(weakSelf)
    LKBaseButton *rightBtn = [LKBaseButton buttonWithFrame:CGRectMake(0, 0, 64, 24) type:UIButtonTypeCustom title:@"暂存" titleColor:COLOR_HEX(0x333333) layercorne:13 font:[UIFont fontWithName:@"PingFangSC-Regular" size: 16] backgroudColor:[UIColor clearColor] AndActionBlock:^(UIButton * _Nonnull btn) {
        weakSelf.inforModel.status = @"6";
        NSDictionary *param = [self.inforModel properties_aps];
        [[LKNetDataManager defaultManager] sendRequestMethod:HTTPMethodPOST serverUrl:ServerlUrl apiPath:MyShopOpenInformationEditUrl header:[LKUserInforTool account].token parameters:param progress:^(NSProgress * _Nullable progress) {
            
        } success:^(BOOL isSuccess, id  _Nullable responseObject) {
           [SVProgressHUD showInfoWithStatus:responseObject[@"msg"]];
            
        } failure:^(NSString * _Nullable errorMessage) {
            
        }];
    }];
    self.navigationItem.rightBarButtonItem = [[UIBarButtonItem alloc] initWithCustomView:rightBtn];
}
/// 创建表单的view
-(void)createFormView{
    WS(weakSelf)
    self.formview = [UFFormView makeFormView:^(UFFormViewMaker * _Nonnull make) {
        make
        .registerRow([LKUFOpenShopHeaderRow class], [LKUFOpenShopHeaderRowCell class])
        .registerRow([LKUFPictureRow class], [LKUFPictureRowCell class])
        .registerRow([LKUFOpenShopBottomButtonRow class], [LKUFOpenShopBottomButtonRowCell class])
        .addSection([UFSection makeSection:^(UFSectionMaker * _Nonnull make) {
            make
            .titleStyle([UFRowTitleStyle makeTitleStyle:^(UFRowTitleStyleMaker * _Nonnull make) {
               make
                .font([UIFont fontWithName:@"PingFangSC-Regular" size:16])
                .color(labelBlackColor)
                .textAlignment(NSTextAlignmentLeft);
            }])
            .valueStyle([UFTextStyle makeTextStyle:^(UFRowTextStyleMaker * _Nonnull make) {
                make
                .textAlignment(NSTextAlignmentRight)
                .font([UIFont fontWithName:@"PingFangSC-Regular" size:16])
                .color(labelBlackColor);
            }])
            .addRowWithBlock(^__kindof UFRow * _Nonnull{
                LKUFOpenShopHeaderRow *row = [[LKUFOpenShopHeaderRow alloc] init];
                row.headerImage = [UIImage imageNamed:@"编组 7"];
                row.height = (WIDTH - 26)/7 + 20;
                return row;
            })
            .addRowWithBlock(^__kindof UFRow * _Nonnull{
                LKUFPictureRow *pictureRow = [[LKUFPictureRow alloc] init];
                pictureRow.pictureNumbers = 3;
                pictureRow.headerTitle = @"二代身份证照片(请上传法人的身份证照)";
                pictureRow.titlesPlaceArray = @[@"+身份证正面照",@"+身份证背面照",@"+手持身份证正面照"];
                pictureRow.picturesArray = [[NSMutableArray alloc] initWithArray:@[weakSelf.inforModel.positive_id_card_img,weakSelf.inforModel.id_card_img,weakSelf.inforModel.hand_id_card_img]];
                pictureRow.height = 250;
                pictureRow.uploadImageBlock = ^(NSInteger selectValue, UIImageView * _Nonnull selecteImageV) {
                    dispatch_group_notify(self->_group, dispatch_get_main_queue(), ^{
                        dispatch_semaphore_signal(self->semaphore);
                        weakSelf.pictureTapSelectIndex = 1;
                        [weakSelf showAlertChooseVc];
                    });
                };
                return pictureRow;
            })
            .addRow([UFTextFieldRow makeTextFieldRow:^(UFTextFieldRowMaker * _Nonnull make) {
                make
                .height(RowHeightDefault)
                .title(@"姓名")
                .name(@"姓名")
                .valueDidChanged(^(__kindof UFRow * _Nonnull row, NSString * _Nonnull value) {
                    weakSelf.inforModel.account_name = value;
                    weakSelf.inforModel.operator_name = value;
                })
                .value(weakSelf.inforModel.operator_name);
            }])
            .addRow([UFTextFieldRow makeTextFieldRow:^(UFTextFieldRowMaker * _Nonnull make) {
                make
                .height(RowHeightDefault)
                .title(@"身份证号码")
                .valueDidChanged(^(__kindof UFRow * _Nonnull row, NSString * _Nonnull value) {
                    weakSelf.inforModel.id_number = value;
                })
                .value(weakSelf.inforModel.id_number);
            }])
            .addRow([UFDatePickerRow makeDatePickerRow:^(UFDatePickerRowMaker * _Nonnull make) {
                make
                .datePickerMode(UIDatePickerModeDate)
                .dateFormat(@"yyyy-MM-dd")
                .title(@"证件开始日期")
                .name(@"ID_startTime")
                .value([NSString stringWithFormat:@"%@",[NSString timestampSwitchTime:[self.inforModel.id_number_start_time integerValue] andFormatter:@"YYYY-MM-dd"]])
                .accessoryType(UFRowAccessoryDisclosureIndicator)
                .valueDidChanged(^(__kindof UFRow * _Nonnull row, NSString * _Nonnull value) {
                    weakSelf.inforModel.id_number_start_time = [NSString stringWithFormat:@"%ld",[NSString timeSwitchTimestamp:value andFormatter:@"YYYY-MM-dd"]];
                });
            }])
            .addRow([UFDatePickerRow makeDatePickerRow:^(UFDatePickerRowMaker * _Nonnull make) {
                make
                .datePickerMode(UIDatePickerModeDate)
                .dateFormat(@"yyyy-MM-dd")
                .title(@"证件结束日期")
                .name(@"ID_endTime")
                .value([NSString stringWithFormat:@"%@",[NSString timestampSwitchTime:[self.inforModel.id_number_end_time integerValue] andFormatter:@"YYYY-MM-dd"]])
                .accessoryType(UFRowAccessoryDisclosureIndicator)
                .valueDidChanged(^(__kindof UFRow * _Nonnull row, NSString * _Nonnull value) {
                    weakSelf.inforModel.id_number_end_time = [NSString stringWithFormat:@"%ld",[NSString timeSwitchTimestamp:value andFormatter:@"YYYY-MM-dd"]];
                });
            }])
            .addRowWithBlock(^__kindof UFRow * _Nonnull{
                LKUFOpenShopBottomButtonRow *buttonRow = [[LKUFOpenShopBottomButtonRow alloc] init];
                buttonRow.height = 250;
                buttonRow.actionBlock = ^{
                    if ([NSString isBlankString:weakSelf.inforModel.positive_id_card_img])  {
                        [SVProgressHUD showInfoWithStatus:@"请选择身份证正面照"];
                        return ;
                    }
                    if ([NSString isBlankString:weakSelf.inforModel.id_card_img])  {
                        [SVProgressHUD showInfoWithStatus:@"请选择身份证反面照"];
                        return ;
                    }
                    if ([NSString isBlankString:weakSelf.inforModel.hand_id_card_img])  {
                        [SVProgressHUD showInfoWithStatus:@"请选择手持身份证正面照"];
                        return ;
                    }
                    if ([NSString isBlankString:weakSelf.inforModel.operator_name])  {
                        [SVProgressHUD showInfoWithStatus:@"请填写姓名"];
                        return ;
                    }
                    if ([NSString isBlankString:weakSelf.inforModel.id_number])  {
                        [SVProgressHUD showInfoWithStatus:@"请填写身份证号码"];
                        return ;
                    }
                    if ([NSString isBlankString:weakSelf.inforModel.id_number_start_time])  {
                        [SVProgressHUD showInfoWithStatus:@"请选择证件开始日期"];
                        return ;
                    }
                    if ([NSString isBlankString:weakSelf.inforModel.id_number_end_time])  {
                        [SVProgressHUD showInfoWithStatus:@"请选择证件结束日期"];
                        return ;
                    }
                    weakSelf.inforModel.status = @"6";
                    NSDictionary *param = [self.inforModel properties_aps];
                    [[LKNetDataManager defaultManager] sendRequestMethod:HTTPMethodPOST serverUrl:ServerlUrl apiPath:MyShopOpenInformationEditUrl header:[LKUserInforTool account].token parameters:param progress:^(NSProgress * _Nullable progress) {
                        
                    } success:^(BOOL isSuccess, id  _Nullable responseObject) {
                       [SVProgressHUD showInfoWithStatus:responseObject[@"msg"]];
                        LKOpenShopStepFourViewController *stepFourVc = [[LKOpenShopStepFourViewController alloc] init];
                        stepFourVc.inforModel = weakSelf.inforModel;
                        [weakSelf.navigationController pushViewController:stepFourVc animated:YES];
                    } failure:^(NSString * _Nullable errorMessage) {
                        
                    }];

                };
                return buttonRow;
            });
        }])
        .addToSuperView(self.view);
    }];
    [self.formview mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.right.equalTo(self.view);
        make.top.equalTo(self.view.mas_top).offset(NAVIGATION_BAR_HEIGHT);
        make.bottom.equalTo(self.view);
    }];
}
-(void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary<UIImagePickerControllerInfoKey,id> *)info{
    NSString *type = [info objectForKey:UIImagePickerControllerMediaType];
    if ([type isEqualToString:@"public.image"]) {

        UIImage *photo = [info objectForKey:UIImagePickerControllerOriginalImage];
        LKUFPictureRow *row = [self.formview findRowInRange:UFMakeRange(0, self.pictureTapSelectIndex)];
        NSLog(@"选中的%ld",row.selectImageV.tag);
        row.selectImageV.superview.userInteractionEnabled = NO;
        row.selectImageV.image = photo;
            self.selcetedUploadImage = row.selectImageV.image;
        dispatch_group_enter(_group);
        dispatch_group_async(_group, dispatch_get_main_queue(), ^{
            [SVProgressHUD showWithStatus:@"图片上传中..."];
        [[LKNetDataManager defaultManager] sendPOSTRequestWithserverUrl:ServerlUrl apiPath:ImageUploadUrl parameters:nil imageArray:@[self.selcetedUploadImage] targetWidth:100 progress:^(NSProgress * _Nullable progress) {
            
                } success:^(BOOL isSuccess, id  _Nullable responseObject) {
        row.selectImageV.superview.userInteractionEnabled = YES;
                    [SVProgressHUD dismiss];
                    if ([responseObject[@"code"] isEqualToString:@"success"]) {
                        if ([NSString isBlankString:responseObject[@"data"]]) {
                            [SVProgressHUD showInfoWithStatus:@"图片未上传成功，请重新选择"];
                            return ;
                        }
                        switch (row.selectImageV.tag - 1000) {
                            case 0:
                            {
                                self.inforModel.positive_id_card_img = responseObject[@"data"];
                            }
                                break;
                            case 1:
                            {
                                self.inforModel.id_card_img = responseObject[@"data"];
                            }
                                break;
                            case 2:
                            {
                                self.inforModel.hand_id_card_img = responseObject[@"data"];
                            }
                                break;
                            default:
                                break;
                        }
                        dispatch_group_leave(self->_group);
                          dispatch_semaphore_wait(self->semaphore, DISPATCH_TIME_FOREVER);
                          NSLog(@"执行结束");
                    }else{
            dispatch_group_leave(self->_group);
                NSLog(@"执行结束");
            [SVProgressHUD showInfoWithStatus:responseObject[@"msg"]];
                    }
            
                } failure:^(NSString * _Nullable error) {
            
                }];
        });

        
    }
    [picker dismissViewControllerAnimated:YES completion:nil];
}

-(void)imagePickerController:(TZImagePickerController *)picker didFinishPickingPhotos:(NSArray<UIImage *> *)photos sourceAssets:(NSArray *)assets isSelectOriginalPhoto:(BOOL)isSelectOriginalPhoto infos:(NSArray<NSDictionary *> *)infos{

    LKUFPictureRow *row = [self.formview findRowInRange:UFMakeRange(0, self.pictureTapSelectIndex)];
    row.selectImageV.superview.userInteractionEnabled = NO;
    NSLog(@"选中的%ld",row.selectImageV.tag);
    row.selectImageV.image = photos[0];
    self.selcetedUploadImage = row.selectImageV.image;
    dispatch_group_enter(_group);
    dispatch_group_async(_group, dispatch_get_main_queue(), ^{
        [SVProgressHUD showWithStatus:@"图片上传中..."];
            [[LKNetDataManager defaultManager] sendPOSTRequestWithserverUrl:ServerlUrl apiPath:ImageUploadUrl parameters:nil imageArray:@[self.selcetedUploadImage] targetWidth:100 progress:^(NSProgress * _Nullable progress) {
        
            } success:^(BOOL isSuccess, id  _Nullable responseObject) {
        row.selectImageV.superview.userInteractionEnabled = YES;
                if ([responseObject[@"code"] isEqualToString:@"success"]) {
                    switch (row.selectImageV.tag - 1000) {
                        case 0:
                        {
                            self.inforModel.positive_id_card_img = responseObject[@"data"];
                        }
                            break;
                        case 1:
                        {
                            self.inforModel.id_card_img = responseObject[@"data"];
                        }
                            break;
                        case 2:
                        {
                            self.inforModel.hand_id_card_img = responseObject[@"data"];
                        }
                            break;
                        default:
                            break;
                    }
                    dispatch_group_leave(self->_group);
                          dispatch_semaphore_wait(self->semaphore, DISPATCH_TIME_FOREVER);
                          [SVProgressHUD dismiss];
                      NSLog(@"执行结束");
                }else{
            NSLog(@"执行结束");
        [SVProgressHUD showInfoWithStatus:responseObject[@"msg"]];
        dispatch_group_leave(self->_group);
                }
        
            } failure:^(NSString * _Nullable error) {
        
            }];
    });

}

@end
